package com.powernode.controller;

import com.powernode.WebUtils.MD5Utils;
import com.powernode.WebUtils.WebMvcUtils;
import com.powernode.commons.Constants;
import com.powernode.commons.Result;
import com.powernode.domain.User;
import com.powernode.service.UserService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;


@RestController
@RequestMapping("login")
public class LoginController {

    @Resource
    private UserService userService;

    /**
     * 完成登录
     */
    @PostMapping("doLogin.do")
    public Result doLogin(String username,String password,String captcha){
        //验证验证码

        //从session里面获得验证码
        Object code = WebMvcUtils.getRequest().getSession().getAttribute(Constants.CAPTCHA_CODE);
        if(code.equals(captcha)){
            //比较用户名和密码
            User user=userService.login(username, MD5Utils.md5(password));
            if(null==user){
               return new Result(-1,"用户名或者密码不正确");
            }
            //把用户放到session里面
            WebMvcUtils.getRequest().getSession().setAttribute(Constants.SESSION_USER_KEY,user);
            return new Result(200,"登录成功");
        }else{
            return new Result(-1,"用户名或者密码不正确");
        }
    }

    /**
     * 退出登录
     */
    @PostMapping("logout.do")
    public Result logout(){
        try {
            WebMvcUtils.getSession().invalidate();
            return new Result(200,"退出成功");
        }catch (Exception e){
            e.printStackTrace();
            return new Result(-1,"退出登录失败");
        }
    }
}
